/**
 * 1.获取MultiData数据，包含轮播图和推荐列表
 * 2.获取轮播图数据
 * 3.渲染轮播图
 */

/*------------------轮播图以及推荐列表--------------------------------- */
//轮播图容器
const bannerContainer = document.querySelector('.hero-slider-active')
// 推荐商品容器
const recommendContainer = document.querySelector('.banner-statistics .mbn-30')

//获取轮播图和推荐栏目数据
function getMultiData() {
    ajax({
        url: "http://123.207.32.32:8000/api/m3/home/multidata",
        //请求成功之后的回调函数
        success: function (result, status, xhr) {
            // console.log(data)
            // console.log(status)
            //获取轮播图数据
            const bannerList = result.data.banner.list
            //渲染轮播图数据
            renderBanners(bannerList)
            //获取推荐数据
            const recommendList = result.data.recommend.list
            //渲染推荐数据
            renderRecommend(recommendList)
        },
    })
}


//轮播图渲染
function renderBanners(bannerList) {
    const bannerHtmlArr = bannerList.map(item => {
        const bannerHtml = `
        <div class="hero-single-slide ">
            <div class="hero-slider-item bg-img" data-bg="${item.image}">
                
                <div class="container">
                    <div class="row">
                        <div class="col-md-12">
                            <div class="hero-slider-content slide-1">
                                <h2>${item.title}</h2>
                                <a href="shop.html" class="btn-hero">立即购买</a>
                            </div>
                        </div>
                    </div>
                </div>
            
            </div>
        </div>`
        return bannerHtml
    })
    const bannerHtmlStr = bannerHtmlArr.join('')
    bannerContainer.innerHTML = bannerHtmlStr
    //更新轮播图
    updateBanner(".hero-slider-active")
}

//渲染推荐
function renderRecommend(recommendList) {
    const recommendHtmlArr = recommendList.map(item => {
        const html = `
        <div class="col-md-3">
            <div class="banner-item mb-30">
                <figure class="banner-thumb">
                    <a href="#">
                        <img src="${item.image}"
                            alt="">
                    </a>
                    <figcaption class="banner-content">
                        <h2 class="text2">${item.title}</h2>
                        <a class="store-link" href="#">买它</a>
                    </figcaption>
                </figure>
            </div>
        </div>`
        return html
    })
    const recommendHtmlStr = recommendHtmlArr.join('')
    recommendContainer.innerHTML = recommendHtmlStr

}

//轮播图和推荐栏目请求渲染
getMultiData()

/*------------------------商品列表列表--------------------------------- */
//加载更多按钮
const loadMoreBtn = document.querySelector('.btn-load-more')
//表示当前激活的商品类型
let currentType = 'pop'
//滚动条滑动的时候是否可以进行再此加载请求网络
let couldLoadMore = true
//商品列表状态
const goodsListState = {
    'pop': {
        nextPage: 1,
        container: document.querySelector('.mtn-40[data-type="pop"]'),
        name: "流行",
        goodsList: []
    },
    'sell': {
        nextPage: 1,
        container: document.querySelector('.mtn-40[data-type="sell"]'),
        name: "热卖",
        goodsList: []
    },
    'new': {
        nextPage: 1,
        container: document.querySelector('.mtn-40[data-type="new"]'),
        name: "新品",
        goodsList: [{
            iid: 'abc',
        }]
    }
}

//获取商品数据
function getGoodsList(type = "pop", page = 1) {
    couldLoadMore = false
    ajax({
        url: `http://123.207.32.32:8000/api/m3/home/data`,
        data: {
            type: type,
            page: page
        },
        success(result) {
            //获取商品列表数据
            const goodsList = result.data.list
            console.log(goodsList)
            //把商品数据保存在goodsListState
            goodsListState[type].goodsList.push(...goodsList)
            //渲染商品数据
            renderGoodsList(goodsList, type)
            goodsListState[type].nextPage++
            setTimeout(function () {
                couldLoadMore = true
            }, 500)

        }
    })
}
//渲染商品数据
/**
 * 把获取的数据渲染到对应的容器内
 * @param {Array} goodsList 网络请求或获得商品数据列表
 * @param {String} type 要渲染的商品的类型 pop,sell,new 
 */
function renderGoodsList(goodsList, type) {
    //根据数据生成html数组
    const goodsListHtmlArr = goodsList.map(item => {
        const discount = parseInt(item.price / parseFloat(item.orgPrice.replace("￥", '')) * 10)
        const discountHtml = discount === 10 ? "" : `<div class="product-label discount"><span>${discount}折</span></div>`
        return `
        <div class="col-lg-3 col-md-4 col-sm-6">
            <div class="product-item mt-40">
                <figure class="product-thumb">
                    <a href="/product-details.html?iid=${item.iid}">
                        <img class="pri-img lazy-load"  src="${loadingImgUrl}" data-src="${item.show.img}" alt="${item.title}">
                    </a>
                    <div class="product-badge">
                        <div class="product-label new">
                            <span>${goodsListState[type].name}</span>
                        </div>
                        ${discountHtml}
                    </div>
                    <div class="button-group">
                        <a href="javascript:void(0)" data-event="fav" data-toggle="tooltip" data-placement="left" title="收藏">
                            <i class="lnr lnr-heart" data-event="fav" data-iid></i>
                        </a>
                        <a href="javascript:void(0)" data-toggle="modal" data-target="#quick_view">
                            <span data-toggle="tooltip" data-placement="left" title="预览">
                                <i class="lnr lnr-magnifier"></i>
                            </span>
                        </a>
                        <a href="javascript:void(0)" data-event='add-cart' data-iid=${item.iid} data-toggle="tooltip" data-placement="left" title="加入购物车">
                            <i class="lnr lnr-cart" data-event='add-cart' data-iid=${item.iid}></i>
                        </a>
                    </div>
                </figure>
                <div class="product-caption">
                    <p class="product-name">
                        <a href="product-details.html">${item.title}</a>
                    </p>
                    <div class="price-box">
                        <span class="price-regular">￥${item.price}</span>
                        <span class="price-old"><del>${item.orgPrice}</del></span>
                    </div>
                </div>
            </div>
        </div>`
    })
    //根据商品类型拿到对应的容器
    const container = goodsListState[type].container
    //把商品的html拼接到容器内
    container.innerHTML += goodsListHtmlArr.join('')
    //处理图片占位
    handleLoadingImg()

}
/**
 * 控制网页要显示的商品类型
 * @param {String} type   pop,sell,new 
 */
function showType(type) { //'pop'
    for (let key in goodsListState) {
        //获取商品类型对应的容器
        const container = goodsListState[key].container
        if (key === type) {
            container.style.display = "flex"
            //判断该类型是否已经请求过
            if (goodsListState[type].nextPage === 1) {
                //没有请求过数据,请求网络，然后渲染
                getGoodsList(type, goodsListState[type].nextPage)
            }
        } else {
            container.style.display = "none"
        }

    }
    //设置全局变量currentType为当前切换的类型
    currentType = type

}



//默认值显示pop类型
showType('pop')


//加载更多功能
//1.使用点击加载更多实现
// loadMoreBtn.onclick = function () {
//     getGoodsList( type)
// }
//2.使用滚动条实现
onscroll = function () {

    const bodyHeight = document.body.offsetHeight
    //页面距离底部的高度
    const h = bodyHeight - scrollY - innerHeight
    if (h <= 700 && couldLoadMore) {
        // console.log('加载更多')
        // console.log(currentType)
        getGoodsList(currentType, goodsListState[currentType].nextPage)
    }
}


/*
//类型按钮容器
const typeBtnsCon = document.querySelector('.type-group')
//通过事件代理监听按钮click事件
typeBtnsCon.addEventListener('click', function (e) {
    const target = e.target
    if (target.tagName === "BUTTON") {
        // console.log(target)
        const type = target.dataset.type
        // console.log(type)
        showType(type)
    }
})
*/

//使用select实现显示内容的切换
const selectEle = document.querySelector('#goods-type')
selectEle.onchange = function () {
    //获取切换的类型
    const type = this.value
    //显示该类型
    showType(type)
}
/*----------------------------通用----------------------------------------- */
//loading占位符地址
const loadingImgUrl = "/img/loading.gif"
//处理图片占位
function handleLoadingImg() {
    //所有的懒加载图片NodeList
    var loazyImgs = document.querySelectorAll('.lazy-load[data-src]')
    // console.log(loazyImgs.length)
    loazyImgs.forEach(img => {
        const imgUrl = img.dataset.src
        img.src = loadingImgUrl
        const newImg = new Image()
        // const newImg = document.createElement('img')
        newImg.src = imgUrl
        newImg.onload = function () {
            img.src = imgUrl
            img.classList.remove("lazy-load")
        }
    })
}
/**
 * 给localStorage设置数据
 * @param {string} key 
 * @param {Object} data 
 */
function setStorage(key, data) {
    const dataStr = JSON.stringify(data)
    localStorage.setItem(key, dataStr)
}
/**
 * 从localStorage获取数据
 * @param {string}} key 
 */
function getStorage(key) {
    const dataStr = localStorage.getItem(key)
    let data
    try {
        data = JSON.parse(dataStr)
    } catch (e) {
        return dataStr
    }
    return data
}
/*------------------------------购物车----------------------------------------- */
//商品容器
const goodsConEle = document.getElementById('goods-con')

//根据商品的iid在goodsListState对象里面去搜索，返回对应商品的数据
function searchGoodsItem(iid) {
    for (let key in goodsListState) {
        const goodsList = goodsListState[key].goodsList
        const goodsItem = goodsList.find(item => item.iid == iid)
        if (goodsItem) {
            return goodsItem
        }
    }
}

goodsConEle.onclick = function (e) {
    const target = e.target
    const event = target.dataset.event
    if (event === 'add-cart') {
        // TODO:
        // 加入购物车逻辑
        //获取iid
        const iid = target.dataset.iid
        const goodsData = searchGoodsItem(iid)
        cart.addToCart(goodsData)
    } else if (event === 'fav') {
        // TODO:
        // 收藏购物车逻辑
    }
}
//购物车数据
/*
const cartGoodsList = [{
        "iid": "1m70y5k",
        "price": "59.00",
        "img": "http://s11.mogucdn.com/mlcdn/c45406/180808_600abce0g8dc8i4f6ic7k27i7837l_640x960.jpg_320x999.jpg",
        "title": "2018秋季新款韩版百搭格子长袖衬衫+前短后长针织气质开衫外套+高腰直筒九分牛仔裤三件套装",
        "type": 2,
        num: 1
    },
    {
        "iid": "1m745k0",
        "price": "68.00",
        "img": "http://s11.mogucdn.com/mlcdn/c45406/180811_1k5hfa6d803575df3lkb6j67l5j3c_640x960.jpg_320x999.jpg",
        "title": "2018秋季新款韩版女装字母印花宽松连帽休闲卫衣搭配松紧腰九分牛仔裤两件套女时尚运动套装潮",
        "type": 2,
        num: 1
    }
]
*/
/*
//打开购物车按钮
const openCartBtn = document.querySelector('.minicart-btn')
//关闭购物车按钮
const closeCartBtn = document.querySelector('.minicart-close')
//遮罩层
const overlay = document.querySelector('.offcanvas-overlay')
//商品容器
const goodsConEle = document.getElementById('goods-con')
//购物车容器
const cartCon = document.querySelector('.minicart-content-box')
//购物车商品容器，用于添加事件代理
let cartListCon = document.querySelector('.minicart-item-wrapper')
//购物车数据在localStorage里面的键
const CART_DATA_KEY = "cartDataKey"
const cartGoodsList = initCartData()

//打开购物车
function openCart(e) {
    e.preventDefault()
    document.body.classList.add('fix');
    document.querySelector(".minicart-inner").classList.add('show')
}
//关闭购物车
function closeCart() {
    document.body.classList.remove('fix');
    document.querySelector(".minicart-inner").classList.remove('show')
};

//绑定事件
(function bindCartEvent() {
    //添加购物车、收藏等功能
    goodsConEle.onclick = function (e) {
        const target = e.target
        const event = target.dataset.event
        if (event === 'add-cart') {
            // TODO:
            // 加入购物车逻辑
            //获取iid
            const iid = target.dataset.iid
            addToCart(iid)
        } else if (event === 'fav') {
            // TODO:
            // 收藏购物车逻辑
        }
    }
    //打开购物车
    openCartBtn.onclick = openCart

    //关闭购物车
    closeCartBtn.onclick = closeCart
    //遮罩层关闭购物车
    overlay.onclick = closeCart
    //购物车删除商品事件更新/绑定
    updateCartEvent()

})()


//更新DOM元素上面的事件
function updateCartEvent() {
    //从新获购物车取商品列表容器
    cartListCon = document.querySelector('.minicart-item-wrapper')
    //从新绑定事件
    cartListCon.addEventListener('click', function (e) {
        //获取到点击的元素
        const target = e.target
        //获取事件类型
        const event = target.dataset.event
        //如果是删除
        if (event === "delete") {
            //获取iid
            const iid = target.dataset.iid
            //调用删除功能
            deleteFromCart(iid)
        }
    })
}

//格式化购物车数据
function formatGoodsItem(goodsData) {
    const cartGoodsItem = {}
    cartGoodsItem.img = goodsData.show.img
    cartGoodsItem.title = goodsData.title
    cartGoodsItem.price = goodsData.price
    cartGoodsItem.num = 1
    cartGoodsItem.iid = goodsData.iid
    return cartGoodsItem
}




//购物车商品html片段生成
function genCartListHtml(goodsArray) {
    const cartListHtmlArr = goodsArray.map(item => {
        return ` 
        <li class="minicart-item">
            <div class="minicart-thumb">
                <a href="product-details.html">
                    <img src="${item.img}" alt="${item.title}">
                </a>
            </div>
            <div class="minicart-content">
                <h3 class="product-name">
                    <a href="product-details.html">${item.title}</a>
                </h3>
                <p>
                    <span class="cart-quantity">${item.num} <strong>&times;</strong></span>
                    <span class="cart-price">￥${item.price}</span>
                </p>
            </div>
            <button class="minicart-remove" data-event="delete" data-iid="${item.iid}"><i class="lnr lnr-cross" data-event="delete" data-iid="${item.iid}"></i></button>
        </li>`
    })
    return cartListHtmlArr.join('')

}
//整个购物车渲染
function renderCart(goodsArray) {
    const cartListHtml = genCartListHtml(goodsArray)
    const cartInfo = computeCart(goodsArray)
    //商品总价
    const totalPrice = cartInfo.totalPrice
    //商品总量
    const totalNum = cartInfo.totalNum
    updateCartIcon(totalNum)
    const html = `
    <div class="minicart-item-wrapper">
        <ul>
            ${cartListHtml}
        </ul>
    </div>

    <div class="minicart-pricing-box">
        <ul>
            <li>
                <span>商品数量</span>
                <span><strong>${totalNum}</strong></span>
            </li>
            <li class="total">
                <span>总价</span>
                <span><strong>￥${totalPrice}</strong></span>
            </li>
        </ul>
    </div>

    <div class="minicart-button">
        <a href="#"><i class="fa fa-shopping-cart"></i>查看购物车</a>
        <a href="#"><i class="fa fa-share"></i>结账</a>
    </div>
    `
    cartCon.innerHTML = html
    //更新事件
    updateCartEvent()
    //通过购物车数据列表到localStorage里面
    setStorage(CART_DATA_KEY, cartGoodsList)
}
//通过默认数据渲染购物车
renderCart(cartGoodsList)

//计算购物车总价和数量
function computeCart(goodsArray) {
    let totalPrice = 0
    let totalNum = 0
    goodsArray.forEach(item => {
        totalPrice += item.price * item.num
        totalNum += item.num
    })
    return {
        totalPrice: totalPrice.toFixed(2),
        totalNum
    }
}

//向购物车添加商品
function addToCart(iid) {
    //判断商品是否已经存在购物车里面
    const oldGoodsItem = cartGoodsList.find(item => item.iid === iid)
    if (oldGoodsItem) {
        //商品已经存在购物车
        oldGoodsItem.num++
    } else {
        const goodsItem = searchGoodsItem(iid)
        //把商品数据格式化成购物车数据，删除不必要的数据
        const cartItem = formatGoodsItem(goodsItem)
        //把购物车数据添加到购物车数据列表
        cartGoodsList.push(cartItem)
    }
    //从新使用购物车列表数据渲染到页面
    renderCart(cartGoodsList)

}

//根据商品的iid在goodsListState对象里面去搜索，返回对应商品的数据
function searchGoodsItem(iid) {
    for (let key in goodsListState) {
        const goodsList = goodsListState[key].goodsList
        const goodsItem = goodsList.find(item => item.iid == iid)
        if (goodsItem) {
            return goodsItem
        }
    }
}
//通过商品的iid查找商品在购物车数据栏的索引
function searchCart(iid) {
    for (let i = 0; i < cartGoodsList.length; i++) {
        const item = cartGoodsList[i]
        if (iid === item.iid) {
            return i
        }
    }
    return -1
}

//在购物车内删除商品
function deleteFromCart(iid) {
    const i = searchCart(iid)
    if (i != -1) {
        //如果找到则删除
        cartGoodsList.splice(i, 1)
        renderCart(cartGoodsList)
    }
}
//更新购物车图片的数字
function updateCartIcon(num) {
    const cartIcon = document.querySelector('.minicart-btn .notification')
    cartIcon.innerText = num
}
//初始化购物车数据，从localStorage里面恢复数据
function initCartData() {
    return getStorage(CART_DATA_KEY) || []
}

// class Cart{

// }
*/